package club.yuit.desktop.ui.widget;

import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import java.awt.*;

/**
 * @author: yuit
 * @date: 2023/12/12 17:53
 */
public class IntNumberField  extends JTextField  implements NumberFiled<Integer>{


    public IntNumberField() {
        validateInput();
    }

    public IntNumberField(String text) {
        super(text);
        validateInput();
    }

    public IntNumberField(int columns) {
        super(columns);
        validateInput();
    }

    public IntNumberField(String text, int columns) {
        super(text, columns);
        validateInput();
    }

    public IntNumberField(Document doc, String text, int columns) {
        super(doc, text, columns);
        validateInput();
    }

    private void validateInput(){
        this.setDocument(new IntNumberDocument());
    }


    @Override
    public Integer getValue() {
        return Integer.valueOf(this.getText());
    }
}

class IntNumberDocument extends PlainDocument {
    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        if (this.isNumeric(str)) {
            super.insertString(offs, str, a);
        } else {
            Toolkit.getDefaultToolkit().beep();
        }
    }

    private boolean isNumeric(String var1) {
        try {
            Integer.valueOf(var1);
            return true;
        } catch (NumberFormatException var3) {
            return false;
        }
    }
}